package top.scsoul.voes.framework.web.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import top.scsoul.voes.common.core.domain.model.LoginUser;
import top.scsoul.voes.common.exception.SystemException;
import top.scsoul.voes.common.core.domain.entity.User;
import top.scsoul.voes.system.mapper.UserMapper;

import javax.validation.Valid;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class UserLoginService {

    private Map<String, String> cacheMap = new ConcurrentHashMap<>();

    public Map<String, String> getCacheMap() {
        return cacheMap;
    }


    @Autowired
    UserMapper userMapper;
    @Lazy
    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 通过loginUser查询单条数据
     *
     * @param loginUser 登录用户
     * @return 实例对象
     */
    public User login(@Valid LoginUser loginUser) {
        String trueCaptcha = cacheMap.get(loginUser.getCaptchaKey());
        String userCaptcha = loginUser.getCaptcha();

        if (trueCaptcha == null) {
            throw new SystemException("验证码已过期");
        }
        if (!trueCaptcha.equals(userCaptcha)) {
            throw new SystemException("验证码错误");
        }
        cacheMap.remove(loginUser.getCaptchaKey());

        User user = userMapper.queryByUsername(loginUser.getUsername());
        if (user == null) {
            log.error("用户不存在");
            throw new SystemException("用户不存在");
        }
        boolean matches = passwordEncoder.matches(loginUser.getPassword(), user.getPassword());
        if (matches) {
            log.info("登录成功");
            return user;
        } else {
            log.error("密码错误");
            log.error("前端：{}", loginUser.getPassword());
            log.error("SQL:{}", user.getPassword());

            throw new SystemException("密码错误");
        }
    }
}
